package org.linlinjava.litemall.admin.web;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.linlinjava.litemall.admin.annotation.RequiresPermissionsDesc;
import org.linlinjava.litemall.admin.util.AdminResponseCode;
import org.linlinjava.litemall.admin.util.Permission;
import org.linlinjava.litemall.admin.util.PermissionUtil;
import org.linlinjava.litemall.admin.vo.PermVo;
import org.linlinjava.litemall.core.util.JacksonUtil;
import org.linlinjava.litemall.core.util.ResponseUtil;
import org.linlinjava.litemall.core.validator.Order;
import org.linlinjava.litemall.core.validator.Sort;
import org.linlinjava.litemall.db.domain.LitemallAdmin;
import org.linlinjava.litemall.db.domain.LitemallPermission;
import org.linlinjava.litemall.db.domain.LitemallRole;
import org.linlinjava.litemall.db.service.LitemallAdminService;
import org.linlinjava.litemall.db.service.LitemallPermissionService;
import org.linlinjava.litemall.db.service.LitemallRoleService;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.constraints.NotNull;
import java.util.*;

import static org.linlinjava.litemall.admin.util.AdminResponseCode.ROLE_NAME_EXIST;
import static org.linlinjava.litemall.admin.util.AdminResponseCode.ROLE_USER_EXIST;

@RestController
@RequestMapping("/admin/role")
@Validated
public class AdminRoleController {

    @Resource
    private LitemallRoleService roleService;
    @Resource
    private LitemallAdminService adminService;
    @Resource
    private ApplicationContext context;
    @Resource
    private LitemallPermissionService permissionService;

    /**
     * 查询角色列表
     */
    @RequiresPermissions("admin:role:list")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "角色查询")
    @GetMapping("/list")
    public Object roleList(String name,
                           @RequestParam(defaultValue = "1") Integer page,
                           @RequestParam(defaultValue = "10") Integer limit,
                           @Sort @RequestParam(defaultValue = "add_time") String sort,
                           @Order @RequestParam(defaultValue = "desc") String order){
        List<LitemallRole> roleList = roleService.querySelective(name, page, limit, sort, order);
        return ResponseUtil.okList(roleList);
    }

    /**
     * 查询所有角色填充下拉框
     */
    @GetMapping("/options")
    public Object options(){
        List<LitemallRole> roleList = roleService.queryAll();
        List<Map<String,Object>> roles = new ArrayList<>(roleList.size());

        for(LitemallRole role : roleList){
            Map<String,Object> map = new HashMap<>(2);
            map.put("value",role.getId());
            map.put("label",role.getName());
            roles.add(map);
        }
        return ResponseUtil.okList(roles);
    }

    /**
     * 验证输入角色名是否为空
     */
    private Object validated(LitemallRole role){
        String name = role.getName();
        if(StringUtils.isEmpty(name)){
            return ResponseUtil.badArgument();
        }
        return null;
    }

    /**
     * 添加角色
     */
    @RequiresPermissions("admin:role:create")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "添加")
    @PostMapping("/create")
    public Object createRole(@RequestBody LitemallRole role){
        Object error = validated(role);
        if(error != null){
            return error;
        }

        if(roleService.checkExist(role.getName())){
            return ResponseUtil.fail(ROLE_NAME_EXIST,"该角色已存在");
        }

        roleService.add(role);
        return ResponseUtil.ok(role);
    }

    /**
     * 角色详情
     */
    @RequiresPermissions("admin:role:read")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "详情")
    @GetMapping("/read")
    public Object roleInfo(@NotNull Integer id){
        LitemallRole role = roleService.findById(id);
        return ResponseUtil.ok(role);
    }

    /**
     * 编辑角色
     */
    @RequiresPermissions("admin:role:update")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "编辑")
    @PostMapping("/update")
    public Object update(@RequestBody LitemallRole role){
        Object error = validated(role);
        if(error != null){
            return error;
        }

        if(roleService.checkExist(role.getName())){
            return ResponseUtil.fail(ROLE_NAME_EXIST,"角色名已存在");
        }

        roleService.updateById(role);
        return ResponseUtil.ok(role);
    }

    /**
     * 删除角色
     */
    @RequiresPermissions("admin:role:delete")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "删除")
    @PostMapping("/delete")
    public Object delete(@RequestBody LitemallRole role){
        List<LitemallAdmin> adminList = adminService.all();

        for(LitemallAdmin admin : adminList){
            //循环获得所有角色id
            Integer[] roles = admin.getRoleIds();
            for(Integer roleId : roles){
                if(roleId.equals(role.getId())){
                    return ResponseUtil.fail(ROLE_USER_EXIST,"已有管理员具备该角色，无法删除");
                }
            }
        }

        roleService.deleteById(role.getId());
        return ResponseUtil.ok();
    }

    private List<PermVo> systemPermissions = null;
    private Set<String> systemPermissionsString = null;

    private List<PermVo> getSystemPermissions(){
        final String basicPackage = "org.linlinjava.litemall.admin";
        if(systemPermissions == null){
            List<Permission> permissions = PermissionUtil.listPermission(context,basicPackage);
            systemPermissions = PermissionUtil.listPermVo(permissions);
            systemPermissionsString = PermissionUtil.listPermissionString(permissions);
        }
        return systemPermissions;
    }

    private Set<String> getAssignedPermissions(Integer roleId){
        Set<String> assignedPermissions = null;
        if(permissionService.checkSuperPermission(roleId)){
            getSystemPermissions();
            assignedPermissions = systemPermissionsString;
        }else{
            assignedPermissions = permissionService.queryByRoleId(roleId);
        }
        return assignedPermissions;
    }

    /**
     * 查看管理员权限详情
     */
    @RequiresPermissions("admin:role:permission:get")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "权限详情")
    @GetMapping("/permissions")
    public Object getPermissions(Integer roleId){
        List<PermVo> systemPermissions = getSystemPermissions();
        Set<String> assignedPermissions = getAssignedPermissions(roleId);

        Map<String,Object> data = new HashMap<>();
        data.put("systemPermissions",systemPermissions);
        data.put("assignedPermissions",assignedPermissions);
        return ResponseUtil.ok(data);
    }

    /**
     * 更新管理员权限
     */
    @RequiresPermissions("admin:role:permission:update")
    @RequiresPermissionsDesc(menu = {"系统管理","角色管理"},button = "编辑管理员权限")
    @PostMapping("/permissions")
    public Object updatePermissions(@RequestBody String body){
        Integer roleId = JacksonUtil.parseInteger(body,"roleId");
        List<String> permissions = JacksonUtil.parseStringList(body,"permissions");
        if(roleId == null || permissions == null){
            return ResponseUtil.badArgument();
        }

        if(permissionService.checkSuperPermission(roleId)){
            return ResponseUtil.fail(AdminResponseCode.ROLE_SUPER_SUPERMISSION,"当前角色的超级权限不能变更");
        }

        permissionService.deleteByRoleId(roleId);
        for(String permission : permissions){
            LitemallPermission litemallPermission = new LitemallPermission();
            litemallPermission.setRoleId(roleId);
            litemallPermission.setPermission(permission);
            permissionService.add(litemallPermission);
        }
        return ResponseUtil.ok();
    }

}
